<?php

namespace App\Http\Controllers\V1;

use App\Models\User;
use App\Support\Code;
use App\Models\VrtsRecord;
use Illuminate\Http\Request;
use App\Http\Resources\VrtsRecordCollection;

class TransferController extends ApiController
{
    /**
     * 转账记录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $user = $this->getUser();
        return $this->success(new VrtsRecordCollection(
            VrtsRecord::where('user_id', $user->id)->where('type', VrtsRecord::TYPE_TRANSFER)
                ->orderByDesc('created_at')->paginate()));
    }

    /**
     * 转账接口
     *
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $to = User::where('wallet_address', $request->address)->first();
        if (!$to) {
            return $this->fail(Code::PARAMETER_ERROR, '对方公钥错误');
        }

        $from = $this->getUser();
        if ($request->value > $from->vrts) {
            return $this->fail(Code::PARAMETER_ERROR, '余额不足');
        }

        // 转账记录
        VrtsRecord::create([
            'user_id' => $from->id,
            'value' => -abs($request->value),
            'address' => $to->wallet_address,
            'type' => VrtsRecord::TYPE_TRANSFER,
            'vrt_value' => abs($request->value) * 0.8
        ]);

        // 收款记录
        VrtsRecord::create([
            'user_id' => $to->id,
            'address' => $from->wallet_address,
            'type' => VrtsRecord::TYPE_RECEIPT,
            'value' => abs($request->value) * 0.8,
            'vrt_value' => abs($request->value) * 0.2
        ]);

        return $this->setMsg('转账成功')->success();
    }
}
